#include "func.h"
#include "dirStack.h"
#include "jiekou.h"
#include <my_header.h>
#include <mysql/mysql.h>
int ls(const dirStack_t *st, MYSQL *mysql, char *result) {
  // 获取当前路径id
  int id = st->idArr[st->index];

  // 查询当前的目录id的parent_id ----
  char sql[4096] = {0};
  sprintf(sql,
          "select filename from file where parent_id = %d and is_deleted=0",
          id);

  int qret = mysql_query(mysql, sql);
  if (qret != 0) {
    fprintf(stderr, "%s:%s", "mysql_query2", mysql_error(mysql));
    exit(-1);
  }

  MYSQL_RES *rows = mysql_store_result(mysql);
  for (unsigned long i = 0; i < mysql_num_rows(rows); i++) {
    MYSQL_ROW row = mysql_fetch_row(rows);
    for (unsigned int j = 0; j < mysql_num_fields(rows); j++) {
      strcat(result, row[j]);
      strcat(result, " ");
      // printf("%s\n",row[j]);
    }
  }

  mysql_free_result(rows);
  return 0;
}

// 绝对路径1. /dir1  2. /dir1/dir2  dir1存在，创建dir2
// 相对路径 dir1
// userName:用户名   dirName：路径名  result：结果 插入相同行报错
int makedir(dirStack_t *st, MYSQL *mysql, const char *userName,
            const char *dirName, char *result) {
  bzero(result, 4096);
  // 绝对路径
  if (strncmp(dirName, "/", 1) == 0) {
    int index; // 记录最后一个/的位置
    for (int i = strlen(dirName); i >= 0; i--) {
      char target = dirName[i];
      if (strcmp(&target, "/") == 0) {
        index = i;
        break;
      }
    }
    char real_dirName[4096] = {0};
    for (int i = index + 1; i < strlen(dirName); i++) {
      real_dirName[i - index - 1] = dirName[i];
    }

    // 在根目录下创建目录
    if (index == 0) {
      int id=st->idArr[0];
      char sql[4096 * 8] = {0};
      sprintf(sql,
              "insert into file "
              "(filename,username,parent_id,type,path,is_deleted)values('%s',"
              "'%s',%d,'d','%s',0)",
              real_dirName, userName,id, dirName);
      int qret = mysql_query(mysql, sql);
      if (qret != 0) {
        if (mysql_errno(mysql) == 1062) {
          sprintf(result, "错误信息：%s", mysql_error(mysql)); // 待测
          return 0;
        }
      }
      // 在其他目录下创建目录
    } else {
      // 获取已存在的路径
      char pre_dirName[4096] = {0};
      strncpy(pre_dirName, dirName, index);

      char sql[4096 * 8] = {0};
      sprintf(sql,
              "select id from file where path='%s' and username='%s' and "
              "type='d' and is_deleted=0",
              pre_dirName, userName);

      int qret = mysql_query(mysql, sql);
      if (qret != 0) {
        if (mysql_errno(mysql) == 1062) {
          sprintf(result, "错误信息：%s", mysql_error(mysql)); // 路径不存在
          return 0;
        }
      }

      // 执行完sql要将数据存储下来
      MYSQL_RES *rows = mysql_store_result(mysql);
      MYSQL_ROW row = mysql_fetch_row(rows);
      int parent_id = 0;
      parent_id = atoi(row[0]); // 获取的类型都是字符串-->整形
      mysql_free_result(rows);  // 每次select读完都要释放

      memset(sql, 0, 4096); // 清空sql
      sprintf(sql,
              "insert into file "
              "(filename,username,parent_id,type,path,is_deleted)values('%s',"
              "'%s',%d,'d','%s',0)",
              real_dirName, userName, parent_id, dirName);
      qret = mysql_query(mysql, sql);
      if (qret != 0) {
        if (mysql_errno(mysql) == 1062) {
          sprintf(result, "错误信息：%s", mysql_error(mysql)); // 待测
          return 0;
        }
      }
    }
 
    // 相对路径
  } else {
    int id = st->idArr[st->index];

    char sql[4096 * 8] = {0};
    sprintf(sql, "select path from file where id=%d", id);
    int qret = mysql_query(mysql, sql);
    if (qret != 0) {
      fprintf(stderr, "%s:%s", "mysql_query1", mysql_error(mysql));
      exit(-1);
    }
    // 执行完sql要将数据存储下来
    MYSQL_RES *rows = mysql_store_result(mysql);
    // 获取一行的内容 id唯一，只有一行内容
    MYSQL_ROW row = mysql_fetch_row(rows);
    /* printf("%s\n",row[0]); */
    char path[4096] = {0};
    strcpy(path, row[0]);
    // 当前目录为/目录不用再加/
    if (strcmp(row[0], "/") == 0) {
      strcat(path, dirName);
    } else {
      strcat(path, "/");
      strcat(path, dirName);
    }

    mysql_free_result(rows);

    // user_name和path设置了唯一键，若该目录存在，插入会报错
    memset(sql, 0, 4096 * 8);
    sprintf(sql,
            "insert into file "
            "(filename,username,parent_id,type,path,is_deleted)values('%s',"
            "'%s',%d,'d','%s',0)",
            dirName, userName, id, path);
    qret = mysql_query(mysql, sql);
    if (qret != 0) {
      if (mysql_errno(mysql) == 1062) {
        printf("错误信息: %s\n", mysql_error(mysql));
        sprintf(result, "错误信息：%s", mysql_error(mysql)); // 待测
        return 0;
      }
    }


  }
  return 0;
}

int removeDir(dirStack_t *st, MYSQL *mysql, const char *userName,
              const char *dirName, char *result) {

  if (strncmp(dirName, "/", 1) == 0) {

    char sql[4096 * 8] = {0};
    sprintf(sql,
            "select id from file where path='%s' and username='%s' and "
            "type='d' and is_deleted=0",
            dirName, userName);

    int qret = mysql_query(mysql, sql);
    if (qret != 0) {
      sprintf(result, "错误信息：%s", mysql_error(mysql)); // 路径不存在
      return 0;
    }

    // 执行完sql要将数据存储下来
    MYSQL_RES *rows = mysql_store_result(mysql);
    if (mysql_num_rows(rows) == 0) {
      sprintf(result, "该目录不存在\n");
      return 0;
    }
    MYSQL_ROW row = mysql_fetch_row(rows);
    int parent_id = 0;
    parent_id = atoi(row[0]); // 获取的类型都是字符串-->整形
    printf("%d\n", parent_id);
    mysql_free_result(rows); // 每次select读完都要释放

    memset(sql, 0, 4096 * 8); // 清空sql
    sprintf(sql,
            "select count(*) from file where parent_id=%d and username='%s' "
            "and is_deleted=0",
            parent_id, userName);

    qret = mysql_query(mysql, sql);
    if (qret != 0) {
      sprintf(result, "错误信息：%s", mysql_error(mysql)); // 待测
      return 0;
    }
    rows = mysql_store_result(mysql);
    row = mysql_fetch_row(rows);
    int num = atoi(row[0]);
    printf("%d\n", num);
    if (num != 0) {
      sprintf(result, "the dir is not empty,delete failed.");
      printf("%s\n", result);
      return 0;
    }
    mysql_free_result(rows);

    int length = strlen(dirName);
    // 只有一个/，删除根目录
    if (length == 1) {
      printf("delete failed: / can not been deleted\n");
      return 0;
    } else {
      // 删除非根目录
      memset(sql, 0, 4096 * 8); // 清空sql
      sprintf(sql, "delete from file where id=%d", parent_id);
      qret = mysql_query(mysql, sql);
      if (qret != 0) {
        sprintf(result, "错误信息：%s", mysql_error(mysql)); // 待测
        return 0;
      }
      // 检测是否删除成功
      my_ulonglong affected = mysql_affected_rows(mysql);
      if (affected == 0) {
        sprintf(result, "提示: 未删除任何行（ID %d不存在）\n", parent_id);
        return 0; // 不算错误，只是没匹配到行
      }

      sprintf(result, "成功删除%lu行\n", affected);
    }
  } else {
    int id = st->idArr[st->index];
    char sql[4096 * 8] = {0};
    sprintf(sql, "select path from file where id=%d", id);
    int qret = mysql_query(mysql, sql);
    if (qret != 0) {
      fprintf(stderr, "%s:%s", "mysql_query1", mysql_error(mysql));
      exit(-1);
    }
    // 执行完sql要将数据存储下来
    MYSQL_RES *rows = mysql_store_result(mysql);
    // 获取一行的内容 id唯一，只有一行内容
    MYSQL_ROW row = mysql_fetch_row(rows);
    char path[4096] = {0}; // 数据库存储的路径
    strcpy(path, row[0]);
    // 当前目录为/目录不用再加/
    if (strcmp(row[0], "/") == 0) {
      strcat(path, dirName);
    } else {
      strcat(path, "/");
      strcat(path, dirName);
    }
    mysql_free_result(rows);

    memset(sql, 0, 4096 * 8);
    sprintf(sql,
            "select id from file where username = '%s' and parent_id=%d and "
            "type='d' and path ='%s' and is_deleted=0",
            userName, id, path);
    qret = mysql_query(mysql, sql);
    if (qret != 0) {
      printf("错误信息: %s\n", mysql_error(mysql));
      sprintf(result, "错误信息：%s", mysql_error(mysql)); // 待测
      return 0;
    }
    // 执行完sql要将数据存储下来
    rows = mysql_store_result(mysql);
    row = mysql_fetch_row(rows);
    int parent_id = 0;
    parent_id = atoi(row[0]); // 获取的类型都是字符串-->整形
    mysql_free_result(rows);  // 每次select读完都要释放

    memset(sql, 0, 4096 * 8); // 清空sql
    sprintf(sql,
            "select count(*) from file where parent_id=%d and username='%s' "
            "and is_deleted=0",
            parent_id, userName);

    qret = mysql_query(mysql, sql);
    if (qret != 0) {
      sprintf(result, "错误信息：%s", mysql_error(mysql)); // 待测
      return 0;
    }
    rows = mysql_store_result(mysql);
    row = mysql_fetch_row(rows);
    int num = atoi(row[0]);
    printf("%d\n", num);
    if (num != 0) {
      sprintf(result, "the dir is not empty,delete failed.");
      printf("%s\n", result);
      return 0;
    }
    mysql_free_result(rows);

    // 删除非根目录
    memset(sql, 0, 4096 * 8); // 清空sql
    sprintf(sql, "delete from file where id=%d", parent_id);
    qret = mysql_query(mysql, sql);
    if (qret != 0) {
      sprintf(result, "错误信息：%s", mysql_error(mysql)); // 待测
      return 0;
    }
    // 检测是否删除成功
    my_ulonglong affected = mysql_affected_rows(mysql);
    if (affected == 0) {
      sprintf(result, "提示: 未删除任何行（ID %d不存在）\n", parent_id);
      return 0; // 不算错误，只是没匹配到行
    }

    sprintf(result, "成功删除%lu行\n", affected);


  }

  return 0;
}
